package thread;

/**
 * 龟兔赛跑
 * @Author Janson
 * @Date 2022/2/24 15:57
 * @Version 1.0
 */
public class Race implements Runnable {
    private String winner;

    @Override
    public void run() {
        for (int i=1;i<=100;i++){
            //让兔子线程 sleep
            if (Thread.currentThread().getName()=="兔子" && i%10==0){
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    System.out.println("线程 sleep 异常");
                }
            }
            System.out.println(Thread.currentThread().getName() + "跑了"+ i +"步");
            //程序终止条件
            boolean flag = gameOver(i);
            if (flag){
                break;
            }
        }
    }
    //判断是否产生了赢家，产生了，程序终止
    private boolean gameOver(int steps){
        //必须要判断winner 是否为空，不判断的话，程序会将另一个线程执行结束才终止
        if (winner != null){
            return true;
        }else if (steps>=100){
            winner = Thread.currentThread().getName();
            System.out.println("最后的赢家:"+ winner);
            return true;
        }
        return false;
    }
    //main方法  主线程
    public static void main(String[] args) {
        Race race = new Race();
         new Thread(race, "乌龟").start();
        Thread rabbit = new Thread(race, "兔子");
        //设置线程的优先级
        //rabbit.setPriority(Thread.MAX_PRIORITY);
        rabbit.start();
    }
}
